package com.wejoy.video.middle.station.data.util.baiduevs;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.ObjectMapper;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.util.DateUtils;
import com.wejoy.video.middle.station.data.util.StringUtils;
import com.wejoy.video.middle.station.data.vo.api.BusinessPointConfigVO;
import com.wejoy.video.middle.station.data.vo.api.DeptNode;
import com.wejoy.video.middle.station.data.vo.evsapi.EvsApiLoginVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Component
public class EvsApiHttpUtils {

    private final static Logger logger = LoggerFactory.getLogger(EvsApiHttpUtils.class);

    private static String DOMAIN;

    private static String PROJECT_USER_NAME ;

    private static String PROJECT_USER_PASSWORD;
    private static String AREAID;

    @Value("${baidu.evs.areaId}")
    public void setAREAID(String AREAID) {
        EvsApiHttpUtils.AREAID = AREAID;
    }
    @Value("${baidu.evs.domain}")
    public void setDOMAIN(String DOMAIN) {
        EvsApiHttpUtils.DOMAIN = DOMAIN;
    }
    @Value("${baidu.evs.userName}")
    public void setProjectUserName(String projectUserName) {
        PROJECT_USER_NAME = projectUserName;
    }
    @Value("${baidu.evs.password}")
    public void setProjectUserPassword(String projectUserPassword) {
        PROJECT_USER_PASSWORD = projectUserPassword;
    }

    //api链接密钥
    private static final String API_SECRET ="dspz5nGD";
    //验证码token
    private static final String ERIFICATIONCODETOKEN ="vcToken_VD3w8EYZ";
    //验证码
    private static final String CODE ="97fz";

    //Cookie前缀
    private static String COOKIE_PREFIX="SAAS_SESSION=";
    private static String VERIFICATIONCODE="/api/v2/verificationCode";
    private static String LOGIN="/api/v2/login";
    private static String LOGINOUT="/api/v2/logout";
    private static String DEPARTMENTS="/api/v2/departments";
    private static String USERS="/api/v2/departments/{departmentId}/users";
    private static String CURRENT_USER_INFO="/api/v2/users/current_user_info";
    private static String USER_BY_ID="/api/v2/users/{id}";
    private static String AREAS="/api/v2/areas";
    private static String POINT_TAG="/api/v2/points/tag";
    private static String PTZ="/api/v2/points/{pointId}?ptz";
    private static String FI="/api/v2/points/{pointId}?fi";
    private static String GET_TAGS="/api/v2/tags";
    private static String GET_AREAS="/api/v2/areas";
    private static String POINTS="/api/v2/points";
    private static String POINTS_SIGNED_URL="/api/v2/points/{pointId}/signed_url";
    private static String POINT_INFO_URL="/api/v2/ai/apps/points/{point_id}/abilities";
    private static String POINT_CONFIG_URL="/api/v2/ai/apps/{algorithm_scene_type}/abilities/{algorithm_ability_type}/points/config";
    private static String GET_POINT_CONFIG_URL="/api/v2/ai/apps/{algorithm_scene_type}/abilities/{algorithm_ability_type}/points/{point_id}/config";
    private static String GET_POINT_RECORDING = "/api/v2/points/{pointId}/recording";
    private static String GET_POINT_LOCAL_RECORDING = "/api/v2/points/{pointId}/localRecording";
    private static final String ACCESSKEY="ec3pns8rwd4wz2dqu7v";
    private static final String SECRETKEY="ec3pd7eag8778prjd17";


    public static HttpResponse postWithHeaders(String url, Map<String, String> headers, String requestBody) {
        HttpRequest request = HttpRequest.post(url)
                .headerMap(headers,false)
                .body(requestBody);
        HttpResponse execute = request.execute();
        if(!execute.isOk()){
            logger.info("evsAPI接口参数 url:"+ url);
            logger.info("evsAPI请求头:"+ JSONObject.toJSONString(headers));
            logger.error("请求EVS—API接口失败headers:{}",JSONObject.toJSONString(execute.headers()));
            logger.error("请求EVS—API接口失败body:{}",JSONObject.toJSONString(execute.body()));
            logger.info("EVS-API接口 result:"+ JSONObject.toJSONString(execute.body()));
            logger.error("请求evsAPI接口失败");
        }
        return execute;
    }

    public static HttpResponse putWithHeaders(String url, Map<String, String> headers, String requestBody) {
        HttpRequest request = HttpRequest.put(url)
                .headerMap(headers, false)
                .body(requestBody);
        HttpResponse response = request.execute();
        if (!response.isOk()) {
            logger.info("evsAPI接口参数 url:"+ url);
            logger.info("evsAPI请求头:"+ JSONObject.toJSONString(headers));
            logger.error("请求EVS—API接口失败headers:{}",JSONObject.toJSONString(response.headers()));
            logger.error("请求EVS—API接口失败body:{}",JSONObject.toJSONString(response.body()));
            logger.info("EVS-API接口 result:"+ JSONObject.toJSONString(response.body()));
            logger.error("请求evsAPI接口失败");
        }
        return response;
    }


    // 发送 GET 请求，并自定义请求头和参数
    public static HttpResponse getWithHeadersAndParams(String url, Map<String, String> headers, Map<String, Object> queryParams) {
        if (queryParams != null && !queryParams.isEmpty()) {
            StringBuilder urlBuilder = new StringBuilder(url);
            if (!url.contains("?")) {
                urlBuilder.append("?");
            } else {
                urlBuilder.append("&");
            }
            urlBuilder.append(buildQueryString(queryParams));
            url = urlBuilder.toString();
        }
        HttpRequest request = HttpRequest.get(url)
                .headerMap(headers, true);

        HttpResponse execute = request.execute();
        logger.info("evsAPI接口参数 url:"+ url);
        logger.info("evsAPI请求头:"+ JSONObject.toJSONString(headers));
        logger.error("请求EVS—API接口失败headers:{}",JSONObject.toJSONString(execute.headers()));
        logger.error("请求EVS—API接口失败body:{}",JSONObject.toJSONString(execute.body()));
        logger.info("EVS-API接口 result:"+ JSONObject.toJSONString(execute.body()));
        if (!execute.isOk()) {
            logger.info("evsAPI接口参数 url:"+ url);
            logger.info("evsAPI请求头:"+ JSONObject.toJSONString(headers));
            logger.error("请求EVS—API接口失败headers:{}",JSONObject.toJSONString(execute.headers()));
            logger.error("请求EVS—API接口失败body:{}",JSONObject.toJSONString(execute.body()));
            logger.info("EVS-API接口 result:"+ JSONObject.toJSONString(execute.body()));
            throw new BusinessException("API請求錯誤！");
        }
        return execute;
    }

    private static String buildQueryString(Map<String, Object> queryParams) {
        StringBuilder queryStringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
            if(entry.getValue()!=null){
                if (queryStringBuilder.length() > 0) {
                    queryStringBuilder.append("&");
                }
                queryStringBuilder.append(entry.getKey()).append("=").append(entry.getValue().toString());
            }
        }
        return queryStringBuilder.toString();
    }
    public static JSONObject getVerificationCode(){
      return JSONObject.parseObject(getWithHeadersAndParams(DOMAIN + VERIFICATIONCODE, null,null).body());
    }

    /**
     * 获取部门
     * @return
     */
    public static JSONObject getDepartments(Integer parentId,Boolean includeLower,String name,String token){
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("parentId",parentId);
        queryParams.put("includeLower",includeLower);
        if(!StringUtils.isEmpty(name)){
            queryParams.put("name",name);
        }
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        return JSONObject.parseObject(getWithHeadersAndParams(DOMAIN + DEPARTMENTS, headers, queryParams).body());
    }

    /**
     * 获取用户列表
     * @return
     */
    public static JSONObject getUsers(Integer departmentId,Integer pageNo,Integer PageSize,String name,String tel,String token){
        if(departmentId==null){
            departmentId=1000204;
        }
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("pageNo",pageNo);
        queryParams.put("pageSize",PageSize);
        if(!StringUtils.isEmpty(name)){
            queryParams.put("name",name);
        }
        if (!StringUtils.isEmpty(tel)){
            queryParams.put("tel",tel);
        }
        return JSONObject.parseObject(getWithHeadersAndParams((DOMAIN + USERS).replace("{departmentId}", departmentId + ""), headers, queryParams).body());
    }

    /**
     * 获取当前用户信息
     * @return
     */
    public static JSONObject getCurrentUserInfo(String token){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        return JSONObject.parseObject(getWithHeadersAndParams(DOMAIN + CURRENT_USER_INFO, headers, null).body());
    }

    /**
     * 获取点位播放链接
     * @param token
     * @param pointId
     * @return
     */
    public static JSONObject pointsSignedUrl(String token,Integer pointId,String protocol){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("protocol",protocol);
        return JSONObject.parseObject(getWithHeadersAndParams((DOMAIN + POINTS_SIGNED_URL).replace("{pointId}",pointId.toString()), headers, queryParams).body());
    }
    /**
     * 获取点位标签信息
     */
    public static JSONObject getPointTagInfo(String token,Long tagId,Integer pageNo,Integer pageSize){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("pageNo",pageNo);
        queryParams.put("pageSize",pageSize);
//        queryParams.put("pointId",pointId);
        queryParams.put("tagId",tagId);
        queryParams.put("includeLowerArea",true);
        queryParams.put("areaId",AREAID);
//        queryParams.put("areaId",1016294);
        return JSONObject.parseObject(getWithHeadersAndParams((DOMAIN + POINT_TAG), headers, queryParams).body());
    }


    /**
     * 获取点位标签信息
     */
    public static JSONObject getPointTagInfoByPointId(String token,Long tagId,Integer pageNo,Long pointId,Integer pageSize){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("pageNo",pageNo);
        queryParams.put("pageSize",pageSize);
        queryParams.put("pointId",pointId);
        queryParams.put("tagId",tagId);
        queryParams.put("includeLowerArea",true);
        queryParams.put("areaId",AREAID);
//        queryParams.put("areaId",1016294);
        return JSONObject.parseObject(getWithHeadersAndParams((DOMAIN + POINT_TAG), headers, queryParams).body());
    }

    /**
     * 获取标签列表信息
     */
    public static JSONObject getTags(String token,Long parentId,String tagCategoryId){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        HashMap<String, Object> queryParams = new HashMap<>();
//        queryParams.put("pageNo",pageNo);
//        queryParams.put("pageSize",pageSize);
        queryParams.put("parentId",parentId);
        queryParams.put("tagCategoryId",tagCategoryId);
        return JSONObject.parseObject(getWithHeadersAndParams((DOMAIN + GET_TAGS), headers, queryParams).body());
    }


    /**
     * 获取点位标签信息
     */
    public static JSONObject getAreas(String token,Long pointId,Integer pageNo,Integer pageSize){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        HashMap<String, Object> queryParams = new HashMap<>();
//        queryParams.put("pageNo",pageNo);
//        queryParams.put("pageSize",pageSize);
//        queryParams.put("pointId",pointId);
        return JSONObject.parseObject(getWithHeadersAndParams(("https://evsretail.bce.baidu.com" + GET_AREAS), headers, queryParams).body());
    }


    /**
     * 获取云端录像列表
     */
    public static JSONObject getCloudRecordList(String token,Integer pointId,Integer pageSize,Integer pageNo,String startTime,String endTime){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("pageSize",pageSize);
        queryParams.put("pageNum",pageNo);
        queryParams.put("beginTime",startTime);
        queryParams.put("endTime",endTime);
        return JSONObject.parseObject(getWithHeadersAndParams((DOMAIN + GET_POINT_RECORDING).replace("{pointId}",pointId.toString()), headers, queryParams).body());
    }

    /**
     * 获取本地录像列表
     */
    public static JSONObject getLocalRecordList(String token,Integer pointId,String startTime,String endTime){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("beginTime",startTime);
        queryParams.put("endTime",endTime);
        queryParams.put("isSync",true);
//        logger.info("请求url："+(DOMAIN + GET_POINT_LOCAL_RECORDING).replace("{pointId}", pointId.toString()));
//        logger.info("请求参数："+JSONObject.toJSONString(queryParams));
        JSONObject jsonObject = JSONObject.parseObject(getWithHeadersAndParams((DOMAIN + GET_POINT_LOCAL_RECORDING).replace("{pointId}", pointId.toString()), headers, queryParams).body());
//        logger.info("请求结果："+jsonObject.toJSONString());
        return jsonObject;
    }

    /**
     * 获取用户信息
     * @return
     */
    public static JSONObject getUserById(Integer id,String token){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        return JSONObject.parseObject(getWithHeadersAndParams((DOMAIN + USER_BY_ID).replace("{id}", id + ""), headers, null).body());
    }

    /**
     * 获取区域
     * @param token
     * @param catalogueId
     * @param parentAreaId
     * @return
     */
    public static JSONObject getAreas(String token,Integer catalogueId,Integer parentAreaId){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        return JSONObject.parseObject(getWithHeadersAndParams(DOMAIN + AREAS, headers,null).body());
    }

    /**
     * 获取点位
     * @param token
     * @param pageSize
     * @param pageNo
     * @param departmentId
     * @return
     */
    public static JSONObject getPoints(String token,Integer pageSize,Integer pageNo,Integer departmentId,String pointName,Boolean includeLowerArea){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("pageSize",pageSize);
        queryParams.put("pageNo",pageNo);
        if(!StringUtils.isEmpty(pointName)){
            queryParams.put("name",pointName);
        }
        if(!ObjectUtils.isEmpty(includeLowerArea)){
            queryParams.put("includeLowerArea",includeLowerArea);
        }
        queryParams.put("departmentId",departmentId);
        String body = getWithHeadersAndParams(DOMAIN + POINTS, headers, queryParams).body();
        return JSONObject.parseObject(body);
    }

    public static JSONObject putPtz(String token,Integer pointId,String ptzCommand,Integer speed){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("ptz","true");
        queryParams.put("ptzCommand",ptzCommand);
        queryParams.put("speed",speed);
        String string = pointId.toString();
        String url = (DOMAIN + PTZ).replace("{pointId}", string);
        if(!StringUtils.isEmpty(ptzCommand)){
            url = url + "&ptzCommand="+ptzCommand;
        }
        if(!ObjectUtils.isEmpty(speed)){
            url = url + "&speed="+speed;
        }
        String body = putWithHeaders(url, headers, JSONObject.toJSONString(queryParams)).body();
        return JSONObject.parseObject(body);
    }


    public static JSONObject fi(String token,Integer pointId,String fiCommand,Integer speed){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("fi","true");
        queryParams.put("fiCommand",fiCommand);
        queryParams.put("speed",speed);
        String string = pointId.toString();
        String url = (DOMAIN + FI).replace("{pointId}", string);
        if(!StringUtils.isEmpty(fiCommand)){
            url = url + "&fiCommand="+fiCommand;
        }
        if(!ObjectUtils.isEmpty(speed)){
            url = url + "&speed="+speed;
        }
        String body = putWithHeaders(url, headers, JSONObject.toJSONString(queryParams)).body();
        return JSONObject.parseObject(body);
    }

    /**
     * 获取点位
     * @param token
     * @param pointId
     * @return
     */
    public static JSONObject getPointsById(String token,Integer pointId){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("pageSize",1);
        queryParams.put("pageNo",1);
        queryParams.put("pointId",pointId);
        return JSONObject.parseObject(getWithHeadersAndParams(DOMAIN + POINTS, headers, queryParams).body());
    }

    public static HttpResponse evsLogin(EvsApiLoginVO loginVO){
        HashMap<String, String> headers = new HashMap<>();
        //base64（用户名 + 连接字符串 + 密码）
        String base64String=loginVO.getName()+API_SECRET+loginVO.getPassword();
//        headers.put("Authorization", encrypt(base64String));
        headers.put("Authorization", Base64.getEncoder().encodeToString(base64String.getBytes()));
        return postWithHeaders(DOMAIN + LOGIN, headers, JSONObject.toJSONString(loginVO));
    }

    public static HttpResponse evsLoginCurrent(){
        EvsApiLoginVO loginVO=new EvsApiLoginVO();
        loginVO.setPassword(PROJECT_USER_PASSWORD);
        loginVO.setName(PROJECT_USER_NAME);
        loginVO.setVerificationCodeToken(ERIFICATIONCODETOKEN);
        loginVO.setVerificationCode(CODE);
        HashMap<String, String> headers = new HashMap<>();
        //base64（用户名 + 连接字符串 + 密码）
        String base64String=loginVO.getName()+API_SECRET+loginVO.getPassword();
//        headers.put("Authorization", encrypt(base64String));
        headers.put("Authorization", Base64.getEncoder().encodeToString(base64String.getBytes()));
        return postWithHeaders(DOMAIN + LOGIN, headers, JSONObject.toJSONString(loginVO));
    }

    // 固定的AES密钥 (16字节)
    private static final byte[] KEY = new byte[]{
            (byte) 0x97, (byte) 0xC4, (byte) 0x4E, (byte) 0x01,
            (byte) 0x93, (byte) 0x9D, (byte) 0xFB, (byte) 0xA2,
            (byte) 0x6F, (byte) 0x7E, (byte) 0x8E, (byte) 0x89,
            (byte) 0x4B, (byte) 0xB9, (byte) 0x40, (byte) 0x8D
    };

    // 固定的初始化向量 (16字节)
    private static final byte[] IV = new byte[]{
            (byte) 0xED, (byte) 0x21, (byte) 0x6C, (byte) 0x52,
            (byte) 0xA9, (byte) 0x60, (byte) 0xEA, (byte) 0x28,
            (byte) 0xF3, (byte) 0x4B, (byte) 0x81, (byte) 0x95,
            (byte) 0xD0, (byte) 0x37, (byte) 0x12, (byte) 0x53
    };

    /**
     * 使用固定AES密钥和IV加密并进行Base64编码
     *
     * @param plaintext 待加密的明文
     * @return 加密后的Base64字符串
     * @throws Exception 如果加密过程中出现错误
     */
    public static String encrypt(String plaintext)  {
        // 初始化AES加密
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        }

        SecretKeySpec secretKeySpec = new SecretKeySpec("b4wp2F6PAeXxl7Va".getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec("T7MjETak4RWt3UiI".getBytes());

        // 加密数据
        try {
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidAlgorithmParameterException e) {
            throw new RuntimeException(e);
        }
        byte[] encrypted = new byte[0];
        try {
            encrypted = cipher.doFinal(plaintext.getBytes());
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        }

        // 转换为Base64
        return Base64.getEncoder().encodeToString(encrypted);
    }

    public static void evsLoginOut(String token){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        postWithHeaders(DOMAIN + LOGINOUT, headers, null);
    }

    /**
     * 获取点位详情
     * @param token
     * @param pointId
     * @return
     */
    public static JSONObject getPointInfo(String token,Long pointId){
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        return JSONObject.parseObject(getWithHeadersAndParams((DOMAIN + POINT_INFO_URL).replace("{point_id}",pointId+""), headers, null).body());
    }

    public static void main(String[] args) {
//        System.out.println(getLocalRecordList("hello" + API_SECRET + "123456"));

//        String token="1000097:440565ff-a710-457c-ae3b-e26e8d793732";
//        System.out.println(getPointConfig("zone_safety", "human_intrusion_detection", 200010716, token));
//        BusinessPointConfigVO businessPointConfigVO = JSONObject.parseObject("{\"analysisStatus\":\"ongoing\",\"isCustomConfig\":true,\"config\":{\"triggerTime\":15000,\"endDelayTime\":20000,\"callbackInterval\":10000,\"confidence\":0.3,\"extractFrameInterval\":5000,\"inArea\":true,\"effectiveTime\":[{\"dayOfWeek\":1,\"beginTime\":\"09:00:00\",\"endTime\":\"21:59:59\"},{\"dayOfWeek\":2,\"beginTime\":\"10:00:00\",\"endTime\":\"21:59:59\"},{\"dayOfWeek\":3,\"beginTime\":\"09:00:00\",\"endTime\":\"21:59:59\"},{\"dayOfWeek\":4,\"beginTime\":\"09:00:00\",\"endTime\":\"21:59:59\"}],\"extractFrameIntervalLabel\":\"5秒\",\"inAreaLabel\":\"区域内\",\"enabled\":true,\"type\":\"human_intrusion_detection\"}}\n", BusinessPointConfigVO.class);
//        businessPointConfigVO.setPointIds(Arrays.asList(200010716));
//        JSONObject jsonObject = businessHallPointConfig("zone_safety", "human_intrusion_detection", businessPointConfigVO, token);
//        System.out.println(ObjectUtils.(jsonObject));
//        evsLoginOut("1003688:7efaf684-574a-450d-82e4-41d2aae30ea5");
//        System.out.println(getCurrentUserInfo("1003688:75d90a1e-a59c-4be2-af02-18362b1675c0"));
//        JSONObject departments = getDepartments(-1, true, "", "1003688:e8f22f3d-b4ee-4f31-9283-569ecbf42db5");
//        System.out.println(getDepartments(-1, true, "", token));
//        System.out.println(JSONArray.toJSONString(convertToDesiredFormat(departments.getJSONArray("data"))));
//        System.out.println(getPoints(token, 10, 1, 1000108,null,null));
//        System.out.println(getUsers(1000099, 1, 5, null,null,"1003688:dc9d1605-4991-4cb1-9cee-e7a91405dd2b"));
//        System.out.println(getUsers(1000099, 1, 5, null,null));
//        System.out.println(getUserById(1003690, "1003688:d6f89826-d9cf-4249-a8f5-da9a29f27ec7"));
//        System.out.println(getAuthToekn(POINTS_SIGNED_URL));
//        System.out.println(getPointInfo("1003688:319fed20-f5aa-43f3-b31e-76425b34c24f", 200027199L));
//        HashMap<String, String> headers = new HashMap<>();
//        headers.put("Cookie",COOKIE_PREFIX+"1003688:5cceaeb3-e0c9-4530-9e0a-255c613c5362");
//        System.out.println(JSONObject.parseObject(getWithHeadersAndParams((DOMAIN + POINT_INFO_URL).replace("{point_id}", 1000001 + ""), headers, null).body()));
//        System.out.println(getWithHeadersAndParams((DOMAIN + POINT_INFO_URL).replace("{point_id}",200027202+""), headers, null));
//        System.out.println(putPtz("1000237:f431105c-e8d2-4fec-9092-694f28ed71e4", 200031178,"right",4));
//        System.out.println(getAreas("1000237:55c9e493-cdaf-4c01-9a01-0aa577abdf32", 200027202L, 1, 10));
    }


    /**
     * 获取部门
     * @return
     */
    public static JSONObject getDepartmentsApi(Integer parentId,Boolean includeLower,String name){
        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("parentId",parentId);
        queryParams.put("includeLower",includeLower);
        if(!StringUtils.isEmpty(name)){
            queryParams.put("name",name);
        }
        String url=DOMAIN + DEPARTMENTS;
        return JSONObject.parseObject(getWithHeadersAndParams(url, getAuthToekn(url), queryParams).body());
    }

    /**
     * 获取用户列表
     * @return
     */
    public static JSONObject getUsers(Integer departmentId,Integer pageNo,Integer PageSize,String name,String tel){
        if(departmentId==null){
            departmentId=1000204;
        }

        HashMap<String, Object> queryParams = new HashMap<>();
        queryParams.put("pageNo",pageNo);
        queryParams.put("pageSize",PageSize);
        if(!StringUtils.isEmpty(name)){
            queryParams.put("name",name);
        }
        if (!StringUtils.isEmpty(tel)){
            queryParams.put("tel",tel);
        }
        String url=(DOMAIN + USERS).replace("{departmentId}", departmentId + "");
        return JSONObject.parseObject(getWithHeadersAndParams((DOMAIN + USERS).replace("{departmentId}", departmentId + ""), getAuthToekn(url), queryParams).body());
    }


    /**
     * 控制营业厅点位AI配置
     * @return
     */
    public static JSONObject businessHallPointConfig(String sceneType, String abilityType, BusinessPointConfigVO businessPointConfigVO, String token){
        String url = DOMAIN+POINT_CONFIG_URL;
        url=url.replace("{algorithm_scene_type}", sceneType);
        url=url.replace("{algorithm_ability_type}", abilityType);
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        return  JSONObject.parseObject(putWithHeaders(url,headers, JSONObject.toJSONString(businessPointConfigVO)).body());
    }

    /**
     * 获取点位AI配置
     * @param sceneType
     * @param abilityType
     * @param pointId
     * @return
     */
    public static JSONObject getPointConfig(String sceneType,String abilityType,Integer pointId,String token){
        String url = DOMAIN+GET_POINT_CONFIG_URL;
        url=url.replace("{algorithm_scene_type}", sceneType);
        url=url.replace("{algorithm_ability_type}", abilityType);
        url=url.replace("{point_id}", pointId+"");
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie",COOKIE_PREFIX+token);
        return  JSONObject.parseObject(getWithHeadersAndParams(url,headers, null).body());
    }

    /**
     * api鉴权authtoken = HMACSHA256("ak;sk;expire;url", ak); HMACSHA256是⼀个通⽤的加密算法
     * @return
     */
    private static HashMap<String, String> getAuthToekn(String url) {
        HashMap<String, String> headers = new HashMap<>();
        long time = new Date().getTime()+300000;
        // 要加密的数据
        String data = ACCESSKEY+";"+SECRETKEY+";"+time+";"+url;
        logger.info("加密字符串:"+data);
        // 使用 HMAC-SHA256 算法
        Mac sha256Hmac = null;
        try {
            sha256Hmac = Mac.getInstance("HmacSHA256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

        // 使用密钥初始化 HMAC
        SecretKeySpec secretKey = new SecretKeySpec(ACCESSKEY.getBytes(), "HmacSHA256");
        try {
            sha256Hmac.init(secretKey);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }

        // 执行 HMAC 算法
        byte[] hmacData = sha256Hmac.doFinal(data.getBytes());
        // 将加密后的字节数组转换为十六进制字符串
        StringBuilder result = new StringBuilder();
        for (byte b : hmacData) {
            result.append(String.format("%02x", b));
        }

        // 将加密后的字节数组转换为 Base64 编码的字符串
        String hmacBase64 = Base64.getEncoder().encodeToString(hmacData);
        headers.put("x-bce-evs-auth-token",hmacBase64);
        headers.put("x-bce-evs-auth-expire-date",time+"");
        headers.put("x-bce-evs-auth-user",ACCESSKEY);
        return headers;
    }


}
